
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);

const viewer = new Cesium.Viewer("cesiumContainer", {
    info: false,
    geocoder: false,
    homeButton: false,
    sceneModePicker: false,
    baseLayerPicker: false,
    navigationHelpButton: false,
    animation: false,
    // creditContainer: "credit",
    timeline: false,
    fullscreenButton: false,
    vrButton: false,
    // terrain: Cesium.Terrain.fromWorldTerrain(),
    imageryProvider: new Cesium.SingleTileImageryProvider({
        url:"",
    }),//影像服务提供者必须创建
});
// 去除cesium的logo
viewer.cesiumWidget.creditContainer.style.display = "none";

// 将原来鼠标中键倾斜视图修改为鼠标左键拖动
viewer.scene.screenSpaceCameraController.tiltEventTypes = [
    Cesium.CameraEventType.RIGHT_DRAG,
];
// 将原来鼠标右键拖动缩放修改为鼠标滚轮滚动
viewer.scene.screenSpaceCameraController.zoomEventTypes = [
    Cesium.CameraEventType.WHEEL,
];

viewer.scene.globe.depthTestAgainstTerrain = true;

// 背景图
let imageryProvider = new Cesium.SingleTileImageryProvider({
    url: './Images/Global.jpg',
});
viewer.imageryLayers.addImageryProvider(imageryProvider);

const infoBox = document.getElementById('infoBox');
const longitudeSpan = document.getElementById('longitude');
const latitudeSpan = document.getElementById('latitude');
// const heightSpan = document.getElementById('height');
const headingSpan = document.getElementById('heading');
const pitchSpan = document.getElementById('pitch');
const rollSpan = document.getElementById('roll');
const heightSpan = document.getElementById('cameraHeight');

// 鼠标移动监听
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction((movement) => {
    const cartesian = viewer.scene.pickPosition(movement.endPosition);
    if (cartesian) {
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
        // const height = cartographic.height.toFixed(2);

        longitudeSpan.innerText = longitude;
        latitudeSpan.innerText = latitude;
        // heightSpan.innerText = height;
    } else {
        longitudeSpan.innerText = 'N/A';
        latitudeSpan.innerText = 'N/A';
        // heightSpan.innerText = 'N/A';
    }
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

// 相机变化监听
viewer.scene.postRender.addEventListener(() => {
    const camera = viewer.camera;

    const heading = Cesium.Math.toDegrees(camera.heading).toFixed(2);
    const pitch = Cesium.Math.toDegrees(camera.pitch).toFixed(2);
    const roll = Cesium.Math.toDegrees(camera.roll).toFixed(2);

    headingSpan.innerText = heading;
    pitchSpan.innerText = pitch;
    rollSpan.innerText = roll;

    const cameraPosition = viewer.camera.positionCartographic;
    const cameraHeight = cameraPosition.height.toFixed(2); // 相机高度（米）
    // 在页面中显示相机高度
    heightSpan.innerText = cameraHeight;
    
});


// 加载高德地图，高德地图存在坐标偏移问题，推荐使用天地图影像
var imgLayer = new Cesium.UrlTemplateImageryProvider({
    url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
    minimumLevel: 3,
    maximumLevel: 18
})
viewer.imageryLayers.addImageryProvider(imgLayer);



// FIXME:加载地形会将河流表面遮挡
// // 加载cesiumlab切好的地形数据
// viewer.scene.setTerrain(new Cesium.Terrain(
//     Cesium.CesiumTerrainProvider.fromUrl('http://127.0.0.1:8081/', {
//         requestWaterMask: true,
//         requestVertexNormals: true
//     })
// ));

let modelList = [];

// 获取文件输入元素
const fileInput = document.getElementById('fileInput');
 
// 监听文件选择事件
fileInput.addEventListener('change', async function(event) {
    // console.log("You have choosed a file.");

    const files = event.target.files;
    if (files.length === 0) {
        alert("请选择至少一个 GLB 文件！");
        return;
    }

    // 逐个处理每个文件
    for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // const file = event.target.files[0];
        if (!file || (!file.name.endsWith(".glb") && !file.name.endsWith(".gltf"))) {
            alert("请选择一个 .glb 或 .gltf 文件！");
            return;
        }
        // 读取 GLB 文件为 Blob URL
        const fileUrl = URL.createObjectURL(file);

        const model = await Cesium.Model.fromGltf({
            url: fileUrl,
            modelMatrix: getHYDModleMatrix(),
            scale: 1,
        });

        modelList.push(model);

    

    // // // 使用 readyPromise 检查加载是否成功
    // // model.readyPromise.then(function (loadedModel) {
    // //     console.log("模型加载成功！", loadedModel);
    // //     // 可以在这里添加其他逻辑，例如飞到模型位置

    // //     // viewer.flyTo(loadedModel);
    // // }).catch(function (error) {
    // //     console.error("模型加载失败！", error);
    // // });

    // // console.log("加载的模型为：", model);

    }

    await loadModelsByTime(modelList);

});


const loadModelsByTime = (modelList)=>{
    let currentModelIndex = 0; // 当前模型索引
    let loadModel = null;// 当前加载的模型

    // 每隔 1 秒加载并显示一个模型
    const intervalId = setInterval(() => {

        if(currentModelIndex>=modelList.length){
            clearInterval(intervalId);  // 停止定时器
            console.log(`加载模型停止，已经加载了${modelList.length}个模型`);
            return;
        }

        // 移除上一个模型
        if (loadModel) {
            viewer.scene.primitives.remove(loadModel);
        }

        // 获取当前模型
        loadModel = modelList[currentModelIndex];
        viewer.scene.primitives.add(loadModel);

        // 更新模型索引
        // currentModelIndex = (currentModelIndex + 1) % modelFiles.length;
        currentModelIndex+=1;

    }, 1000);
}


function getHYDModleMatrix(){
    const longitude = 114.60210557096437;
    const latitude = 30.57613451056752;
    // const height = 121.0;


    const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, -10);
    // 针对中国区域的旋转情况
    const heading = Cesium.Math.toRadians(90);//在地球表面（东西南北方向上），绕南北方向旋转
    const pitch = Cesium.Math.toRadians(90);//在垂直及东西方向的平面上，绕垂直方向旋转
    const roll = Cesium.Math.toRadians(0);//在垂直向上及南北方向面上，绕垂直方向旋转
    // const orientation = Cesium.Transforms.headingPitchRollQuaternion(position, new Cesium.HeadingPitchRoll(heading, pitch, roll));

    let matrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, new Cesium.HeadingPitchRoll(heading, pitch, roll));
    return matrix
}

const cameraLon = 113.955282;
const cameraLat = 30.206550;
const cameraHeight = 135000.0;
const cameraPosition = Cesium.Cartesian3.fromDegrees(cameraLon, cameraLat, cameraHeight);

// 设置相机视图
viewer.camera.setView({
    destination: cameraPosition,
    orientation: {
        heading: Cesium.Math.toRadians(345),
        pitch: Cesium.Math.toRadians(-90),
        roll: 0
    }
});